package com.yksj.healthtalk.ui.doctor;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unionpay.UPPayAssistEx;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.PayActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.comm.WalletPayFragmentDialog;
import com.yksj.healthtalk.comm.WalletPayFragmentDialog.OnClickSureBtnListener;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.setting.SettingPhoneBound;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.MD5Utils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.wallet.PwdSettingActivity;

/**
 * (医生中 VIP服务 网上咨询 门诊预约)   选择支付方式
 * @author Administrator
 *
 */
public class SelectPaymentOptionActivity extends BaseFragmentActivity  implements OnClickSureBtnListener, OnDilaogClickListener, OnClickListener{
	
	private String url;
	private TextView mWalletMoney;
	private CustomerInfoEntity mCustomerInfoEntity;
	 private static final int PLUGIN_NOT_INSTALLED = -1;
	    private static final int PLUGIN_NEED_UPGRADE = 2;

	    /*****************************************************************
	     * mMode参数解释：
	     *      "00" - 启动银联正式环境
	     *      "01" - 连接银联测试环境
	     *****************************************************************/
	    private String mMode = "00";
	    private static final String TN_URL_01 = "http://222.66.233.198:8080/sim/gettn";
		private Boolean isBindPhone;
		private Boolean isSetPsw;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.select_payment_option);
		initWidget();
		initDate();
	}
  
	private void initDate() {
		url = getIntent().getStringExtra("url");
		mCustomerInfoEntity = (CustomerInfoEntity) getIntent().getExtras().get("mCustomerInfoEntity");
		String  money = getIntent().getStringExtra("money");
		if (!TextUtils.isEmpty(money)) {
			findViewById(R.id.wallet_lin).setVisibility(View.VISIBLE);
			mWalletMoney.setText("余额:"+money+"元");
		}
//		{"BindPhone":"1","Balance":"1","isSetPsw":"1"}
		String FLAG;
		isBindPhone = !TextUtils.isEmpty( FLAG = getIntent().getStringExtra("BindPhone")) && FLAG.equals("1");	
		isSetPsw = !TextUtils.isEmpty( FLAG = getIntent().getStringExtra("isSetPsw")) && FLAG.equals("1");	
	}

	private void initWidget() {
		initTitle();
		CoreService.actionLogin(SelectPaymentOptionActivity.this);
		titleTextV.setText("选择支付方式");
		titleLeftBtn.setOnClickListener(this);
		mWalletMoney = (TextView) findViewById(R.id.wallet_money);
		findViewById(R.id.onclick_alipay).setOnClickListener(this);
		findViewById(R.id.onclick_unionpay).setOnClickListener(this);
	}
	
	@Override
	protected void onStart() {
		HttpRestClient.doHttpGetQianBao(SmartFoxClient.getLoginUserId(), new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, String content) {
				try {
					JSONObject response = JSON.parseObject(content);
					if (response.containsKey("Balance")) {
						findViewById(R.id.wallet_lin).setVisibility(View.VISIBLE);
						mWalletMoney.setText("余额:"+response.getString("Balance")+"元");
					}
				} catch (Exception e) {
				}
				super.onSuccess(statusCode, content);
			}
		});
		super.onStart();
//		Intent intent =new Intent(this,CoreService.class);
//		intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
//		intent.putExtra("className",this.getClass().getName());
//		startService(intent);
	}
	
	/**
	 * 钱包
	 * @param v
	 */
	public void onClickWallet(View v){
		if (!isBindPhone) {
			DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  "使用钱包支付，需绑定手机并设置支付密码，您目前未绑定手机。", "稍后再说", "现在绑定", this);
		}else if(!isSetPsw){
			DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  "使用钱包支付，需绑定手机并设置支付密码，您目前未设置支付密码。", "稍后再说", "现在设置", this);
		}else {
			WalletPayFragmentDialog.show(getSupportFragmentManager(), "输入支付密码","" );
		}
	}
	
	class AyncHander extends AsyncHttpResponseHandler{
		private String type;

		public AyncHander(String string) {
			super(SelectPaymentOptionActivity.this);
			this.type = string;
		}
		@Override
		public void onSuccess(int statusCode, String content) {
			try {
				JSONObject response = JSON.parseObject(content);
				if (response.containsKey("error_message")) {
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), response.getString("error_message"));
					return;
				}else  if (type.equals("Wallet")) {
					if (!response.containsKey("error_message")) {
						FriendHttpUtil.onItemClick(SelectPaymentOptionActivity.this, mCustomerInfoEntity);
					}
				}else if(response.containsKey("tn")){
//					{"PAY_ID":"1140227007141885","tn":"201402271420460080192"}
					  /************************************************* 
		             * 
		             *  步骤2：通过银联工具类启动支付插件 
		             *  
		             ************************************************/
		            // mMode参数解释：
		            // 0 - 启动银联正式环境
		            // 1 - 连接银联测试环境
		            int ret = UPPayAssistEx.startPay(SelectPaymentOptionActivity.this, null, null, response.getString("tn"), mMode);
		            if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
		                // 需要重新安装控件
		                AlertDialog.Builder builder = new AlertDialog.Builder(SelectPaymentOptionActivity.this);
		                builder.setTitle("壹健康");
		                builder.setMessage("完成购买需要安装银联支付控件，是否安装？");
		                builder.setNegativeButton("确定",
		                        new DialogInterface.OnClickListener() {
		                            @Override
		                            public void onClick(DialogInterface dialog,
		                                    int which) {
		                                dialog.dismiss();
		                                UPPayAssistEx.installUPPayPlugin(SelectPaymentOptionActivity.this);
		                            }
		                        });

		                builder.setPositiveButton("取消",
		                        new DialogInterface.OnClickListener() {

		                            @Override
		                            public void onClick(DialogInterface dialog,
		                                    int which) {
		                                dialog.dismiss();
		                            }
		                        });
		                builder.create().show();
		            }else {
						finish();
					}
				}else if(response.containsKey("LING")){//价格为0 跳转到 聊天界面
					FriendHttpUtil.onItemClick(SelectPaymentOptionActivity.this, mCustomerInfoEntity);
				}
			} catch (Exception e) {
				if (content.contains("支付宝")) {
					Intent intent = new Intent(getApplicationContext(),PayActivity.class);
					intent.putExtra("summary", content);
					intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
					startActivity(intent);
				}
			}
			super.onSuccess(statusCode, content);
		}
	}
	
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1 && resultCode == RESULT_OK) {
			isSetPsw = true;
		}else if(requestCode == 2 && resultCode == RESULT_OK){
			if (data.hasExtra("phone_num")) {
				isBindPhone = true;
			}else {
				isBindPhone = false;
			}
		}else {
			/************************************************* 
	         * 
	         *  步骤3：处理银联手机支付控件返回的支付结果 
	         *  
	         ************************************************/
	        if (data == null) {
	            return;
	        }

	        String msg = "";
	        /*
	         * 支付控件返回字符串:success、fail、cancel
	         *      分别代表支付成功，支付失败，支付取消
	         */
	        String str = data.getExtras().getString("pay_result");
	        if (str.equalsIgnoreCase("success")) {
	            msg = "支付成功！";
	        } else if (str.equalsIgnoreCase("fail")) {
	            msg = "支付失败！";
	        } else if (str.equalsIgnoreCase("cancel")) {
	            msg = "用户取消了支付";
	        }

	        SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  msg);
		}
		super.onActivityResult(requestCode, resultCode, data);
    }

	@Override
	public void onClickSureHander(String pwd) {
		if (TextUtils.isEmpty(pwd)) {
			ToastUtil.showShort(getApplicationContext(), "密码不能为空");
		}else {
			String str[] = url.split("&");
			for (int i = 0; i < str.length; i++) {
				if (str[i].contains("Type")) {
					str[i] = "Type=WalletPayment";
				}
			}
			StringBuilder builder = new StringBuilder();
			for (int i = 0; i < str.length; i++) {
				builder.append(str[i]);
				builder.append("&");
			}
			url = builder.toString().substring(0, builder.toString().length()-1);
			HttpRestClient.doHttpWalletPay(url,MD5Utils.getMD5(pwd), new AyncHander("Wallet"));
		}
	}

	@Override
	public void onDismiss(DialogFragment fragment) {
	}

	@Override
	public void onClick(DialogFragment fragment, View v) {
		// TODO Auto-generated method stub
		if (!isBindPhone) {
			Intent intent = new  Intent(this, SettingPhoneBound.class);
			startActivityForResult(intent, 2);
		}else if(!isSetPsw){
			Intent intent = new Intent(getApplicationContext(), PwdSettingActivity.class);
			intent.putExtra("isPayPwd", isSetPsw);
			intent.putExtra("isBDPhoneNum", SmartFoxClient.getLoginUserInfo().getPoneNumber());
			startActivityForResult(intent, 1);
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.onclick_alipay://支付宝
			HttpRestClient.doHttpGetAliPay(url, new AyncHander("Alipay"));
			break;
		case R.id.onclick_unionpay://银联
			HttpRestClient.doHttpGetUnionPay(url, new AyncHander("Unionpay"));
			break;
		}
		
	}
	
	
}
